package Client;

import XMLPack.FileParserI;
import Graphic.MainForm;
import XMLPack.SaxParser;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;


// Design pattern Singelton
public class Client implements Runnable
{
    private Socket socket;
    private String serverAddress;
    private int port;
    private BufferedReader in= null;
    private OutputStream out = null;
    private FileParserI parser = null;
    private static Client client = null;


    String fileName = "localTemp.xml";    
    MainForm form = null;


     public Client getInstance(MainForm f)
    {
        if(client == null)
            return new Client(f);
        else return client;
    }
     public static Client getInstance(MainForm f, String servA, int port)
    {
        if(client == null)
        {
            client = new Client(f, servA, port);
            return client;
        }
        else return client;
    }
     
     public String getTempName()
     {
        long unixTime = System.currentTimeMillis() / 1000L;
        System.out.println("temp\\"+unixTime+".xml");
        return "temp\\"+unixTime+".xml";

     }
    private Client(MainForm f)
    {
        super();
        socket = null;
        serverAddress = "127.0.0.1";
        port = 8005;
        Connect();

    }
   
    private Client(MainForm f, String serverAddress, int port)
    {
        super();
        this.serverAddress = serverAddress;
        this.port = port;
        socket = null;
        form = f;
        Connect();
    }

    private int Connect()
    {
        try
        {
            socket = new Socket(serverAddress, port);
           // out = socket.getOutputStream();
        }
        catch (UnknownHostException ex)
        {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            return -1;
        }
        catch (IOException ex)
        {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            return -1;
        }

        return 0;
    }

   


    public void SetRequest(String file)
    {       

        System.out.println("SetRequest "+file);
           fileName = file;
           Thread th = new Thread(this);
           th.start();

          if(fileName.compareTo("exit") == 0)
          {
               Clear();
          }
     }

 public void Clear()
  {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("clear ...");

    }

    public void run ()
    {

        try
        {
            out = socket.getOutputStream();
            out = new PrintStream(socket.getOutputStream());

            // Trimitem un fisier la server:)
                File f = new File(fileName);
                FileInputStream file = new FileInputStream(f);

                byte[] buffer = new byte[socket.getSendBufferSize()];

                int bytesRead = 0;

                while((bytesRead = file.read(buffer))>0)
                {
                    out.write(buffer,0,bytesRead);
                    System.out.write(buffer,0,bytesRead);
                    
                }
                out.flush();
                  file.close();
                  f.delete();


            // primeste raspuns
                InputStream input = socket.getInputStream();
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                 System.out.println("input stream: "+ in);
                 String fileName  = getTempName();
                FileOutputStream wr = new FileOutputStream(new File(fileName) );

                buffer = new byte[socket.getReceiveBufferSize()];
                int bytesReceived = 0;

                
                 
             do{
                // Write to the file
                     bytesReceived = input.read(buffer);
                     System.out.write(buffer,0,bytesReceived);
                     wr.write(buffer,0,bytesReceived);
                    }while(bytesReceived  == socket.getReceiveBufferSize());

              

                parser = new SaxParser(form);
                parser.list(fileName);
                wr.close();


        }

        catch(IOException e)
        {
            System.out.println("IOException"+ e);
        }
        /*catch ( UnknownHostException e)
        {
            System . err. println (" Serverul nu poate fi gasit \n" + e);
            System . exit (1);
        }*/

    }

    public static void main(String args[])
   {
      /*  Client cl= null;
        cl = new Client();
        cl.SetRequest("C2S.txt");*/

   }

    public FileParserI getParser(){return parser;}
    public void setParser(SaxParser p){parser = p;}
   /* public String getParserAnswer()
    {

        int i = 0;
        return null;
        //return parser.getAnswer();
    }*/
    
    @Override
    public String toString()
    {
        return socket.toString()+" "+serverAddress+" "+port+" "+in+
                " "+out+" "+parser;
    }
}


